package com.example.wangda.smart_home_android_v12;

import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.util.Log;

import com.chinamobile.iot.onenet.mqtt.MqttCallBack;
import com.chinamobile.iot.onenet.mqtt.MqttClient;
import com.chinamobile.iot.onenet.mqtt.MqttConnectOptions;
import com.chinamobile.iot.onenet.mqtt.MqttService;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttConnAck;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttMessage;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttPublish;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttSubAck;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttSubscribe;
import com.chinamobile.iot.onenet.mqtt.protocol.imp.QoS;
import com.chinamobile.iot.onenet.mqtt.protocol.imp.Type;

import static com.chinamobile.iot.onenet.mqtt.protocol.imp.QoS.AT_LEAST_ONCE;
import static com.chinamobile.iot.onenet.mqtt.protocol.imp.QoS.AT_MOST_ONCE;


/**
 * Created by wangda on 2017/10/23.
 */

public class MqttHandle {
    private final static String TAG = "MqttHandle";
    /**
     * Created by wangda on 2017/10/20.
     */
    private Context context;
    public MqttHandle(Context context){
            this.context = context;
            mqtt_init(context);
        }
        MqttThread mMqttThread;
        public void mqtt_init(Context context) {
            try {
                String apikey = "Yd9VgMbOlERW5qX7MtQnSGk5kfU=";
                String clientId = "19946427";
                String product_id = "99461";
                // 1、初始化SDK
                MqttClient.initialize(context, "183.230.40.39", 6002, clientId, product_id, apikey);
                // 2、设置接收响应的回调
                MqttClient.getInstance().setCallBack(callBack);
                // 3、设置连接属性(eg:心跳包。选填,可以不设置,调用connect()方法)
                MqttConnectOptions connectOptions = new MqttConnectOptions();
                connectOptions.setCleanSession(true);
                connectOptions.setKeepAlive(200);
                connectOptions.setWill(false);
                connectOptions.setWillQoS(AT_MOST_ONCE);
                connectOptions.setWillRetain(false);
                // 4、建立TCP连接
                MqttClient.getInstance().connect(connectOptions);
            }catch (RuntimeException e)
            {
                Log.e(TAG, "MQTT Err:" + e.toString());
            }
            mMqttThread = new MqttThread(context);
        }

        //创建回调函数（用来接收MQTT消息，继承CallBack接口）
        private MqttCallBack callBack = new MqttCallBack() {
            @Override
            public void messageArrived(MqttMessage msg) {
                //连接响应
                if (msg.getMqttHeader().getType() == Type.CONNACK) {
                    //MqttConnAck mqttConnAck = (MqttConnAck) msg;
                    //启动MQTT_PRO处理线程
                    mMqttThread.StartThread();
                    MainActivity.Log_out("收到ONENET主机的连接完成回应");
                    //透传消息 server->client
                } else if (msg.getMqttHeader().getType() == Type.PUBLISH) {
                    GlobalData.SetMqttConnextSta(GlobalData.networkConnect);
                    //MqttPublish mqttPublish = (MqttPublish) msg;
                    try {
                        String topic = ((MqttPublish) msg).getTopicName();
                        int msgId = ((MqttPublish) msg).getMsgID();
                        byte[] data = ((MqttPublish) msg).getData();
                        MqttPublishDateHandle(topic, msgId, data);
                        MainActivity.Log_out("收到服务器消息");
                    }catch (ClassCastException e)
                    {
                        MainActivity.Log_out(e.toString());
                    }
                    //订阅响应
                } else if (msg.getMqttHeader().getType() == Type.SUBACK) {
                    //MqttSubAck mqttSubAck = (MqttSubAck) msg;
                    MainActivity.Log_out("收到ONENET主机的订阅成功回应");
                    //心跳响应
                } else if (msg.getMqttHeader().getType() == Type.PINGRESP) {
                    MainActivity.Log_out("收到ONENET主机的PINGRESP");
                    //发布响应QOS1
                } else if (msg.getMqttHeader().getType() == Type.PUBACK) {
                    MainActivity.Log_out("收到ONENET主机的发布回应");
                    //发布响应QOS2
                } else if (msg.getMqttHeader().getType() == Type.PUBCOMP) {
                    MainActivity.Log_out("收到ONENET主机的PUBCOMP");
                    //
                }
            }
            //网络异常导致的断开
            @Override
            public void connectionLost(Exception e) {
                MainActivity.Log_out("网络异常导致的断开");
                //UserConnect();
                GlobalData.SetMqttConnextSta(GlobalData.networkUnConnect);
            }
            //连接断开
            @Override
            public void disconnect() {
                MainActivity.Log_out("连接断开");
                //UserConnect();
                GlobalData.SetMqttConnextSta(GlobalData.networkUnConnect);
            }
        };
        /*连接MQTT服务器*/
        public void UserConnect()
        {
            try {
                MqttClient.getInstance().disconnect();

                String apikey = "Yd9VgMbOlERW5qX7MtQnSGk5kfU=";
                String clientId = "19946427";
                String product_id = "99461";
                MainActivity.Log_out("MQTT 尝试重连");
                // 1、初始化SDK
                MqttClient.initialize(context, "183.230.40.39", 6002, clientId, product_id, apikey);
                // 2、设置接收响应的回调
                MqttClient.getInstance().setCallBack(callBack);
                MqttConnectOptions connectOptions = new MqttConnectOptions();
                connectOptions.setCleanSession(true);
                connectOptions.setKeepAlive(200);
                connectOptions.setWill(false);
                connectOptions.setWillQoS(AT_MOST_ONCE);
                connectOptions.setWillRetain(false);
                // 4、建立TCP连接
                MqttClient.getInstance().connect(connectOptions);
            }catch (RuntimeException e)
            {
                Log.e(TAG, "MQTT Err：" + e.toString());
            }
        }
        /*断开连接MQTT服务器*/
        public void UserUnconnect()
        {
            MqttClient.getInstance().disconnect();
        }

        /*控制终端灯泡*/
        public void UserCtrlStairLight(String str)
        {
            try {
                MqttPublish user_publish = new MqttPublish("STAIRS_host", str.getBytes(), AT_MOST_ONCE);
                MqttClient.getInstance().sendMsg(user_publish);
            }catch(RuntimeException e){
                Log.e(TAG, "MQTT Err:" + e.toString());
            }
        }

        /*向平台发送呼吸消息*/
        public void UserKeepAlive()
        {
            try {
                MqttPublish user_publish = new MqttPublish("$dp",3,"{\"keepA\":\"1\"}".getBytes(),AT_MOST_ONCE);
                MqttClient.getInstance().sendMsg(user_publish);
            }catch(RuntimeException e){
                Log.e(TAG, "MQTT Err:" + e.toString());
            }
        }

        /*先平台发送进门事件*/
        public void UserEnterDoor()
        {
            try {
                MqttPublish user_publish = new MqttPublish("$dp",3,"{\"enterDoor\":\"1\"}".getBytes(),AT_MOST_ONCE);
                MqttClient.getInstance().sendMsg(user_publish);
            }catch(RuntimeException e){
                Log.e(TAG, "MQTT Err:" + e.toString());
            }
        }

        private void MqttPublishDateHandle(String topic, int msgId, byte[] data)
        {
            String strData = new String(data).trim();

            final String keepalive = "KEEPALIVE";
            final String S1_TRIG = "S1_TRIG";
            final String S2_TRIG = "S2_TRIG";
            final String CM1_OP = "CM1_OP";
            final String CM1_CL = "CM1_CL";
            final String CM2_OP = "CM2_OP";
            final String CM2_CL = "CM2_CL";
                switch (topic)
                {
                    case MqttPro.Topic_Door:
                         MainActivity.Log_out("recv Topic_Door date ：" + strData);
                        /*呼吸*/
                         if(strData.equals(keepalive)){
                             GlobalData.SetDoorDeviceOnlineSta(GlobalData.CountDown);
                         }
                         /*门口感应*/
                         if(strData.equals(S1_TRIG)){
                             if(GlobalData.ReadEnterTheDoor() == 0)GlobalData.SetEnterTheDoor(GlobalData.EnterTheDoorDelay);
                             Log.d(TAG, "收到门口感应事件");
                         }
                        break;
                    case MqttPro.Topic_Stairs:
                        MainActivity.Log_out("recv Topic_Stairs date ：" + new String(data));
                        /*呼吸*/
                        if(strData.equals(keepalive)){
                            GlobalData.SetStairsDeviceOnlineSta(GlobalData.CountDown);
                        }
                         /*楼道感应*/
                        if(strData.equals(S1_TRIG)){
                            GlobalData.SetUpTheStairs(GlobalData.StairsLightDelay);
                            Log.d(TAG, "收到楼道感应事件");
                        }
                        break;
                    case MqttPro.Topic_Bed:
                        MainActivity.Log_out("recv Topic_Bed date ：" + new String(data));
                        if(strData.equals(keepalive)){
                            GlobalData.SetBedDeviceOnlineSta(GlobalData.CountDown);
                        }
                        break;
                    case MqttPro.Topic_Book:
                        MainActivity.Log_out("recv topic_Book date ：" + new String(data));
                        if(strData.equals(keepalive)){
                            GlobalData.SetBookDeviceOnlineSta(GlobalData.CountDown);
                        }
                        break;
                    default:
                        break;
                }

        }
    }
